<!-- pages/news.vue -->
<template>
  <div class="news-wrap">
    <Navbar />
    <img src="@/assets/images/news-bg.png" alt="news" />

    <img
      src="@/assets/images/ic-news-title.png"
      alt="newsTitle"
      class="w-[442.72px] h-[152px] absolute left-[168px] top-[216px]"
    />

    <div class="content">
      <!-- 新闻列表 -->
      <span class="news-title">
        <div class="news-line"></div>
        幻引新闻资讯
      </span>
      <span class="text-[18px] text-[#7D7D7D] ml-[161px] mt-[9px]"
        >掌握幻引最新动态让技术更好地服务社会，打造支持不同场景、不同方向的智能应用程序</span
      >

      <transition-group
        v-if="newsItems && newsItems.length"
        name="fade-up"
        tag="ul"
        class="mt-[50px] gap-[20px] grid grid-cols-3 w-[1200px] ml-[auto] mr-[auto]"
      >
        <li
          v-for="(newItem, index) in newsItems"
          :key="index"
          :style="{
            animationDelay: cardAnimationDelay(index),
          }"
          class="card-item-transition w-[365px]"
        >
          <nuxt-link
            :to="newItem['内容']"
            target="_blank"
            rel="noopener noreferrer"
          >
            <div
              class="card-item w-[365px] h-[480px] flex flex-col hover:scale-105 transform-gpu"
            >
              <img
                :src="newItem['封面图'] || newItem['封面图']"
                alt="news"
                referrerpolicy="no-referrer"
                class="bg-gray-50 w-[316px] h-[160px] ml-auto mr-auto mt-[25px] object-cover object-top"
              />
              <span
                class="text-[#9D9D9D] text-[14px] mt-[15px] ml-[25px] mr-[25px]"
                >{{ newItem['发布日期'] }}</span
              >
              <span
                class="text-[#2E2D2E] font-semibold text-[24px] mt-[20px] ml-[25px] mr-[25px] line-clamp-2"
                >{{ newItem['标题'] }}</span
              >
              <span
                class="text-[#2E2D2E] text-[18px] mt-[10px] ml-[25px] mr-[25px] line-clamp-2"
                >{{ newItem['副标题'] }}</span
              >

              <span
                class="text-[18px] mt-[24px] ml-[25px] text-[#1955F7] group-hover:text-[#333333] underline"
                >查看详情</span
              >
            </div>
          </nuxt-link>
        </li>
      </transition-group>
      <div
        v-else
        class="min-h-[480px] relative mt-[50px] w-[1200px] ml-[auto] mr-[auto]"
      >
        <CustomLoading />
      </div>
    </div>

    <Pagination
      :totalItems="totalItems"
      :itemsPerPage="itemsPerPage"
      :currentPage="currentPage"
      @update:currentPage="updateCurrentPage"
      @update:itemsPerPage="updateItemsPerPage"
    />
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import Navbar from '~/components/navbar.vue'
import CustomLoading from '~/components/custom-loading.vue'
import { useCustomLoading } from '~/composables/useCustomLoading'
const { startLoading, endLoading } = useCustomLoading()
// 导入 userApi 实例
import userApi from '@/api/index'
import { useState } from '#app'

const newsCount = useState('newsCount', () => 0)
const newsItems = ref([])
const totalItems = ref(newsCount) // 示例总条数
const itemsPerPage = ref(9) // 示例每页条数
const currentPage = ref(1) // 示例当前页码

// 定义 emit
const emit = defineEmits(['update-footer-style'])
const cardAnimationDelay = computed(() => {
  return (index) => `${(index + 1) * 0.2}s`
})
// 第几页
const updateCurrentPage = (page) => {
  currentPage.value = page
  console.log(page)
  handleNews()
}

onMounted(() => {
  emit('update-footer-style', '#2F274C', '#FFFFFF')
  currentPage.value = 1 // 重置当前页码
  handleNews()
})
// 每页多少条
const updateItemsPerPage = (items) => {
  itemsPerPage.value = items
  currentPage.value = 1 // 重置当前页码
  console.log(items)
  handleNews()
}
async function handleNews() {
  try {
    const userId = localStorage.getItem('user_id')
    if (!userId) {
      return
    }
    // if (newsItems.value < currentPage.value) {
    //   return
    // }
    startLoading()
    newsItems.value = []
    const response = await userApi.askQuestions(
      `data=查看新闻列表，根据发布日期倒排，每页${itemsPerPage.value}条，第${currentPage.value}页&session_id=1&endpoint_id=${userId}&是否有效=1`,
    )
    if (response) {
      const res = JSON.parse(response)
      // console.log('getNews successful:', res.data)
      const action_text = JSON.parse(res.data.action_text)
      // console.log(action_text.data)
      await nextTick()
      newsItems.value = action_text.data
    }
    endLoading()
  } catch (error) {
    endLoading()
    console.error('getNews failed:', error)
    // 处理登录失败后的逻辑
  }
}
</script>
<style scoped>
.news-wrap {
  display: flex;
  flex-direction: column;
  background: white;
  justify-content: space-between;
  align-items: center;
  min-height: calc(100vh - 110px);
  position: relative;
}

.content {
  flex: 1;
  width: 100%;
  min-height: 480px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.news-title {
  display: flex;
  align-items: center;
  margin-left: 161px;
  letter-spacing: -2%;
  font-size: 32px;
  font-weight: 600;
}

.news-line {
  width: 6px;
  height: 30px;
  background-color: #1955f7;
  margin-right: 10px;
}

.card-item-transition {
  opacity: 0;
  transform: translateY(20px);
  animation: fadeInUp 0.5s forwards;
}

.card-item {
  box-shadow: 0px 4px 16px 0px rgba(0, 0, 0, 0.15);
  background: rgb(255, 255, 255);
  cursor: pointer;
}

@keyframes fadeInUp {
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, 100%, 0);
    transform: translate3d(0, 100%, 0);
  }

  100% {
    opacity: 1;
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
  }
}
</style>
